// components/upload-file/upload-File.js
import {uploadFile, deleteFile} from "../../service/File";
import Notify from "@vant/weapp/notify/notify";
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        savePath: { //存储地址
            type: String,
            value: "record/"
        },
        required: { //是否标记为必传
            type: Boolean,
            value: false
        },
        title: { //标题
            type: String,
            value: ""
        },
        maxCount: { //上传数量限制
            type: Number,
            value: 1
        },
        maxSize: { //文件大小限制 2M
            type: Number,
            value: 2 * 1024 * 1024
        },
        imgSecCheck: { //开启图片内容合法验证
            type: Boolean,
            value: true
        },
        fileList: { //接收的图片数据
            type: Array,
            value: []
        },
        border: { //是否显示底部边框
            type: Boolean,
            value: true
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        _fileList: [], //文件列表
        _isAllowDeleteAll: true  //是否可以删除全部图片
    },

    /*
      * 监听
      * */
    observers: {
        "fileList": function (value) {
            const that = this;
            if (value.length > 0) { //处于编辑状态
                that.data._isAllowDeleteAll = false; //不允许删光
                that.setData({
                    "_fileList": that.data.fileList.map(function (item) {
                        item.url = item.id;
                        item.status = "done";
                        return item
                    })
                })
            }
        }
    },

    /**
     * 组件的方法列表
     */
    methods: {
        /*
        * 图片上传
        * */
        onUploaderAfterRead: function (e) { //读取成功
            const that = this;
            let fileList = that.data._fileList;
            let newArr = e.detail.file.map(function (item) {
                return {
                    url: item.path,
                    status: "uploading",
                    message: "上传中"
                }
            })
            fileList.push.apply(fileList, newArr);
            that.setData({_fileList: fileList});
            let promiseArr = newArr.map(async function (item) {
                try {
                    let id = await uploadFile({
                        savePath: that.data.savePath,
                        filePath: item.url,
                    }, that.data.imgSecCheck)
                    return({
                        id: id,
                        status: "done"
                    })
                } catch (e) {
                    console.error(e)
                    return({
                        id: "",
                        status: "failed",
                        message: e.errCode === 87014 ? "非法内容" : "上传失败"
                    })
                }
            });
            Promise.all(promiseArr).then(function (res) {
                let fileList = that.data._fileList;
                let newArr = fileList.splice(-res.length);
                for (let i = 0; i < newArr.length; i ++) {
                    newArr[i].status = res[i].status;
                    newArr[i].id = res[i].id || "";
                    newArr[i].message = res[i].message || "";
                }
                fileList.push.apply(fileList, newArr);
                that.setData({_fileList: fileList}, function () {
                    that._sendMessage()
                })
            })
        },

        /*
        * 图片删除
        * */
        onUploaderDelete: async function (e) { //删除
            const that = this;
            let list = that.data._fileList;
            let current = e.detail.index;
            try {
                if (!that.data._isAllowDeleteAll && that.data.required && list.length === 1) {
                    throw ("请先上传更换的图片，再删除多余图片");
                }
                if (list[current].status === "uploading") {
                    throw ("正在上传，请等待上传结束")
                }
                if (list[current].id) {
                    that.setData({
                        ["_fileList[" + current + "].status"]: "uploading",
                        ["_fileList[" + current + "].message"]: "删除中..."
                    })
                    await deleteFile([list[current].id]);
                }
                list.splice(e.detail.index, 1);
                that.setData({_fileList: list}, function () {
                    that._sendMessage()
                })
            } catch (e) {
                if (e.name) { //有错误类型
                    that.setData({
                        ["_fileList[" + current + "].status"]: "done",
                        ["_fileList[" + current + "].message"]: "已完成"
                    })
                    console.error(e)
                } else {
                    Notify({
                        context: that,
                        selector: "#van-notify_upload",
                        message: e || "删除失败"
                    });
                }
            }
        },

        /*
        * 文件超出大小限制
        * */
        onUploaderOversize: function () {
            Notify({
                context: this,
                selector: "#van-notify_upload",
                message: "文件大小不能超过2M"
            });
        },

        /*
        * 通知父组件
        * */
        _sendMessage: function () {
            this.triggerEvent("uploadFile", {
                status: "success",
                result: this.data._fileList.filter(function (item) {
                    return item.id
                })
            }, {}); //组件接收函数写入数据
        }
    }
})
